<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>商品管理</title>
	<meta name="decorator" content="default"/>
	<script type="text/javascript">
		$(document).ready(function() {
			var $tableDiv = $("#tableDiv");
			var $productTable = $("#productTable");
			var $specificationTable = $(".specificationTable");
			var hasSpecification = false;
			var initProductValues = {};
			$tableDiv.hide();
			
			<c:if test="${goods.sis!=null}">
				<c:forEach items="${products }" var="product" varStatus="status">
				  
				</c:forEach>
			</c:if>
			//alert("4444:"+${goods.sis!=null});
			//此处将要是商品规格加载的功能
			
			
			// 选择规格
			$specificationTable.on("change", "input:checkbox", function() {
				$tableDiv.show();
				if ($specificationTable.find("input:checkbox:checked").size() > 0) {
					hasSpecification = true;
				} else {
					hasSpecification = false;
				}
				var $this = $(this);
				var value = $.trim($this.val());
				buildProductTable();
			});
			// 规格
			$specificationTable.on("change", "input:text", function() {
				var $this = $(this);
				var value = $.trim($this.val());
				if (value == "") {
					$this.val($this.data("value"));
					return false;
				}
				if ($this.hasClass("specificationItemEntryValue")) {
					var values = $this.closest("tr").find("input.specificationItemEntryValue").not($this).map(function() {
						return $.trim($(this).val());
					}).get();
					if ($.inArray(value, values) >= 0) {
						$this.val($this.data("value"));
						return false;
					}
				}
				$this.data("value", value);
				buildProductTable();
			});
			// 是否默认
			$productTable.on("change", "input.isDefault", function() {
				var $this = $(this);
				if ($this.prop("checked")) {
					$productTable.find("input.isDefault").not($this).prop("checked", false);
				} else {
					$this.prop("checked", true);
				}
			});
			
			// 是否启用
			$productTable.on("change", "input.isEnabled", function() {
				var $this = $(this);
				if ($this.prop("checked")) {
					$this.closest("tr").find("input:not(.isEnabled)").prop("disabled", false);
				} else {
					$this.closest("tr").find("input:not(.isEnabled)").prop("disabled", true).end().find("input.isDefault").prop("checked", false);
				}
				if ($productTable.find("input.isDefault:not(:disabled):checked").size() == 0) {
					$productTable.find("input.isDefault:not(:disabled):first").prop("checked", true);
				}
			});
			// 生成商品表
			function buildProductTable(productValues) {
				var specificationItems = [];
				if (!hasSpecification) {
					$tableDiv.hide();
					$productTable.empty();
					return false;
				}
				$specificationTable.each(function() {
					var $this = $(this);
					var $checked = $this.find("input:checkbox:checked");
					if ($checked.size() > 0) {
						var specificationItem = {};
						//alert("规格名："+$this.parent().find(".specname").val());
						specificationItem.name = $this.parent().find(".specname").val();
						specificationItem.entries = $checked.map(function() {
							return {
								id: $(this).siblings("input.specificationItemEntryId").val(),
								value: $(this).siblings("input.specificationItemEntryValue").val()
							};
						}).get();
						specificationItems.push(specificationItem);
					}
				});	
				var products = cartesianProductOf($.map(specificationItems, function(specificationItem) {
					return [specificationItem.entries];
				}));
				$titleTr = $('<tr><th width=50 >是否启用<\/th><\/tr>').appendTo($productTable.empty());
				$.each(specificationItems, function(i, specificationItem) {
					$titleTr.append('<th>' + specificationItem.name + '<\/th>');
				});
				$titleTr.append('<th>价格<\/th><th>库存<\/th>');
				$.each(products, function(i, entries) {
		            var ids = [];
		            $productTr = $('<tr><td><input type="checkbox" name="isEnabled" class="isEnabled" value="true"' + (isEnabled ? ' checked="checked"' : '') + ' \/><\/td><\/tr>').appendTo($productTable);
		            $.each(entries, function(j, entry) {
		                $productTr.append('<td>' + entry.value + '<input type="hidden" name="productList[' + i + '].specificationValues[' + j + '].id" value="' + entry.id + '" \/><input type="hidden" name="productList[' + i + '].specificationValues[' + j + '].value" value="' +entry.value + '" \/><\/td>');
		                ids.push(entry.id);
		            });
		            var productValue = productValues[ids.join(",")];
		            var price = productValue != null && productValue.price != null ? productValue.price : "";
		            var cost = productValue != null && productValue.cost != null ? productValue.cost : "";
		            var marketPrice = productValue != null && productValue.marketPrice != null ? productValue.marketPrice : "";
		            var rewardPoint = productValue != null && productValue.rewardPoint != null ? productValue.rewardPoint : "";
		            var exchangePoint = productValue != null && productValue.exchangePoint != null ? productValue.exchangePoint : "";
		            var stock = productValue != null && productValue.stock != null ? productValue.stock : "";
		            var isEnabled = productValue != null && productValue.isEnabled != null ? productValue.isEnabled : false;
		            $productTr.append('<td><input type="text" name="productList[' + i + '].price" class="text price" value="' + price + '" maxlength="16" style="width: 50px;" \/><\/td><td><input type="text" name="productList[' + i + '].stock" class="text stock" value="' + stock + '" maxlength="9" style="width: 50px;" \/><\/td>').data("ids", ids.join(","));
		            if (!isEnabled) {
		                $productTr.find(":input:not(.isEnabled)").prop("disabled", true);
		            }
		        });
				
				
				if ($productTable.find("input.isDefault:not(:disabled):checked").size() == 0) {
					$productTable.find("input.isDefault:not(:disabled):first").prop("checked", true);
				}
			}
			// 笛卡尔积
			function cartesianProductOf(array) {
				function addTo(current, args) {
					var i, copy;
					var rest = args.slice(1);
					var isLast = !rest.length;
					var result = [];
					for (i = 0; i < args[0].length; i++) {
						copy = current.slice();
						copy.push(args[0][i]);
						if (isLast) {
							result.push(copy);
						} else {
							result = result.concat(addTo(copy, rest));
						}
					}
					return result;
				}
				return addTo([], array);
			}
			
			//$("#name").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
		});
	</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/shop/goods/">商品列表</a></li>
		<li class="active"><a href="${ctx}/shop/goods/form?id=${goods.id}">商品<shiro:hasPermission name="shop:goods:edit">${not empty goods.id?'修改':'添加'}</shiro:hasPermission><shiro:lacksPermission name="shop:goods:edit">查看</shiro:lacksPermission></a></li>
	</ul><br/>
	<form:form id="inputForm" modelAttribute="goods" action="${ctx}/shop/goods/save" method="post" class="form-horizontal">
		<form:hidden path="id"/>
		<sys:message content="${message}"/>		
		<div class="control-group">
			<label class="control-label">商品分类：</label>
			<div class="controls">
                ${goods.goodsCategory.name}
                <input type="hidden" name="goodsCategoryId" value="${goods.goodsCategory.id }">
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">类型：</label>
			<div class="controls">
				${fns:getDictLabel(goods.type, 'shop_goods_type', '')}
                <input type="hidden" name="type" value="${goods.type }">
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">货号：</label>
			<div class="controls">
				<form:input path="sn" htmlEscape="false" maxlength="255" class="input-xlarge required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">商品名称：</label>
			<div class="controls">
				<form:input path="name" htmlEscape="false" maxlength="255" class="input-xlarge required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">副标题：</label>
			<div class="controls">
				<form:input path="caption" htmlEscape="false" maxlength="255" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">价格：</label>
			<div class="controls">
				<form:input path="price" htmlEscape="false" class="input-xlarge required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">市场价：</label>
			<div class="controls">
				<form:input path="marketPrice" htmlEscape="false" class="input-xlarge required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">销售价：</label>
			<div class="controls">
				<form:input path="sales" htmlEscape="false" maxlength="20" class="input-xlarge required digits"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">单位：</label>
			<div class="controls">
				<form:input path="unit" htmlEscape="false" maxlength="255" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">重量：</label>
			<div class="controls">
				<form:input path="weight" htmlEscape="false" maxlength="11" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">是否需要物流：</label>
			<div class="controls">
				<form:radiobuttons path="isDelivery" items="${fns:getDictList('yes_no')}" itemLabel="label" itemValue="value" htmlEscape="false" class="required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">是否上架：</label>
			<div class="controls">
				<form:radiobuttons path="isMarketable" items="${fns:getDictList('yes_no')}" itemLabel="label" itemValue="value" htmlEscape="false" class="required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">是否置顶：</label>
			<div class="controls">
				<form:radiobuttons path="isTop" items="${fns:getDictList('yes_no')}" itemLabel="label" itemValue="value" htmlEscape="false" class="required"/>
				<span class="help-inline"><font color="red">*</font> </span>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">关键字：</label>
			<div class="controls">
				<form:input path="keyword" htmlEscape="false" maxlength="255" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">封面图：</label>
			<div class="controls">
				<form:hidden id="image" path="image" htmlEscape="false" maxlength="255" class="input-xlarge"/>
				<sys:ckfinder input="image" type="thumb" uploadPath="/shop/goods" maxHeight="750" maxWidth="1920" selectMultiple="false"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">图片集：</label>
			<div class="controls">
				<form:hidden id="productImages" path="productImages" htmlEscape="false" class="input-xlarge"/>
				<sys:ckfinder input="productImages" type="images" uploadPath="/shop/goods" selectMultiple="true"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">商品标签：</label>
			<div class="controls">
				<form:radiobuttons path="shopTag" items="${sts }" itemLabel="name" itemValue="name"/>
			</div>
		</div>
		<c:forEach items="${specifications }" var="specification" varStatus="status">
			<div class="control-group">
				<label class="control-label">${specification.name }：
				</label>
				 <input type="hidden" class="specname" name="specificationItems[${status.index }].name" value="${specification.name }" style="width: 50px;" />
				<div class="controls specificationTable">
					<c:forEach items="${specification.specificationItemList }" var="specificationItem" varStatus="statusItem">
						<span>
							<input type="checkbox" name="specificationItems[${status.index}].entries[${statusItem.index}].isSelected" value="true" >${specificationItem.name }
							<input type="hidden" name="_specificationItems[${status.index}].entries[${statusItem.index}].isSelected" value="false" />
							<input type="hidden" name="specificationItems[${status.index}].entries[${statusItem.index}].id" value="${specificationItem.id}" class="specificationItemEntryId"/>
							<input type="hidden" name="specificationItems[${status.index}].entries[${statusItem.index}].value" value="${specificationItem.name}" class="specificationItemEntryValue"/>
						</span>
					</c:forEach>
				</div>
			</div>
		</c:forEach>
		<div class="control-group" id="tableDiv">
			<label class="control-label"></label>
			<div class="controls">
				<table id="productTable" class="table table-striped table-bordered table-condensed">
					<thead>
						<tr>
							<th class="hide"></th>
							<th>名称</th>
							<th>排序</th>
							<th>备注信息</th>
						</tr>
					</thead>
					<tbody>
						<tr id="attributeItemList{{idx}}">
							<td class="hide">
							</td>
							<td>
							</td>
							<td>
							</td>
							<td>
							</td>
						</tr>
					</tbody>
					<tfoot>
					</tfoot>
				</table>
			</div>
		</div>
		<c:choose>  
		    <c:when test="${!empty goods.parameterValues }">
		    	<c:forEach items="${goods.parameterValues }" var="para" varStatus="status">
					<div class="control-group">
						<label class="control-label">${para.group }：
							<input type="hidden" name="parameterValues[${status.index }].group" class="text parameterGroup" value="${para.group }" maxlength="200" />
						</label>
						<div class="controls">
						    <table class="table table-striped table-bordered table-condensed">
								<thead>
									<tr>
										<th>参数名</th>
										<th>参数值</th>
									</tr>
								</thead>
								<tbody>
									<c:forEach items="${para.entries }" var="parameterItem" varStatus="statusitem">
									<tr>
										<td>
										${parameterItem.name }：
										<input type="hidden" name="parameterValues[${status.index }].entries[${statusitem.index }].name" class="text parameterEntryName" value="${parameterItem.name }" maxlength="200" style="width: 50px;" />
										</td>
										<td>
										<input type="text" name="parameterValues[${status.index }].entries[${statusitem.index }].value" class="text parameterEntryValue" value="${parameterItem.value }" maxlength="200" \/>
										</td>
									</tr>	
									</c:forEach>
								</tbody>
								<tfoot>
								</tfoot>
							</table>
						</div>
					</div>
				</c:forEach>
		    </c:when>  
		    <c:otherwise>
		    	<c:forEach items="${parameters }" var="para" varStatus="status">
					<div class="control-group">
						<label class="control-label">${para.name }：
							<input type="hidden" name="parameterValues[${status.index }].group" class="text parameterGroup" value="${para.name }" maxlength="200" />
						</label>
						<div class="controls">
						    <table class="table table-striped table-bordered table-condensed">
								<thead>
									<tr>
										<th>参数名</th>
										<th>参数值</th>
									</tr>
								</thead>
								<tbody>
									<c:forEach items="${para.parameterItemList }" var="parameterItem" varStatus="statusitem">
									<tr>
										<td>
										${parameterItem.name }：
										<input type="hidden" name="parameterValues[${status.index }].entries[${statusitem.index }].name" class="text parameterEntryName" value="${parameterItem.name }" maxlength="200" style="width: 50px;" />
										</td>
										<td>
										<input type="text" name="parameterValues[${status.index }].entries[${statusitem.index }].value" class="text parameterEntryValue" maxlength="200" \/>
										</td>
									</tr>	
									</c:forEach>
								</tbody>
								<tfoot>
								</tfoot>
							</table>
						</div>
					</div>
				</c:forEach>
		    </c:otherwise>  
		 </c:choose>
		<div class="control-group">
			<label class="control-label">筛选属性：</label>
			<div class="controls">
				<c:forEach items="${attributes }" var="attr">
					${attr.name }:
					<select name="attribute_${attr.id}">
						<c:forEach items="${attr.attributeItemList }" var="attributeItem">
							<option value="${attributeItem.name }" <c:if test="${attributeItem.name == goods.getAttributeValue(attr) }">selected="selected"</c:if>>${attributeItem.name }</option>
						</c:forEach>
					</select>
				</c:forEach>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">品牌：</label>
			<div class="controls">
				<form:select path="brand.id" class="input-xlarge required" items="${brands }" itemLabel="name" itemValue="id"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">积分：</label>
			<div class="controls">
				<form:input path="score" htmlEscape="false" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">商品描述：</label>
			<div class="controls">
				<form:textarea id="introduction" path="introduction" htmlEscape="true" rows="4" class="input-xxlarge "/>
				<sys:ckeditor replace="introduction" uploadPath="/shop/goods"></sys:ckeditor>
			</div>
		</div>
		<div class="control-group">
            <label class="control-label">自定义内容视图:</label>
            <div class="controls">
                  <form:select path="customContentView" class="input-medium">
                      <form:option value="" label="默认视图"/>
                      <form:options items="${contentViewList}" htmlEscape="false"/>
                  </form:select>
                  <span class="help-inline">自定义内容视图名称必须以"${goods_DEFAULT_GOODSVIEW}"开始</span>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">自定义视图参数:</label>
            <div class="controls">
                  <form:input path="viewConfig" htmlEscape="true"/>
                  <span class="help-inline">视图参数例如: {count:2, title_show:"yes"}</span>
            </div>
        </div>
		<div class="control-group">
			<label class="control-label">seo description：</label>
			<div class="controls">
				<form:input path="seoDescription" htmlEscape="false" maxlength="255" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">seo keywords：</label>
			<div class="controls">
				<form:input path="seoKeywords" htmlEscape="false" maxlength="255" class="input-xlarge "/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">seo title：</label>
			<div class="controls">
				<form:input path="seoTitle" htmlEscape="false" maxlength="255" class="input-xlarge "/>
			</div>
		</div>
		<div class="form-actions">
			<shiro:hasPermission name="shop:goods:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/>&nbsp;</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
		</div>
	</form:form>
</body>
</html>